package com.quanyan.user.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbCommentMapper;
import com.quanyan.user.mapper.TbNewsDetailsMapper;
import com.quanyan.user.model.db.TbComment;
import com.quanyan.user.model.db.TbCommentExample;
import com.quanyan.user.model.db.TbNewsDetails;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.vo.request.ReqNewsComment;
import com.quanyan.user.model.vo.request.ReqNewsCommentDel;
import com.quanyan.user.model.vo.request.UnReadParam;
import com.quanyan.user.model.vo.response.ImageObj;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/11/15.
 */
@Service
public class NewsCommentServiceImpl implements NewsCommentService {

    private static final Logger logger = LoggerFactory.getLogger(NewsCommentServiceImpl.class);

    @Autowired
    private TbNewsDetailsMapper tbNewsDetailsMapper;

    @Autowired
    private TbCommentMapper tbCommentMapper;

    @Autowired
    private DynamicCommentService dynamicCommentService;

    @Autowired
    private SendMsgService sendMsgService;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private NewsImagesService newsImagesService;

    @Autowired
    private NewsUnReadService newsUnReadService;

//    @Autowired
//    private SensitiveServiceFacade sensitiveServiceFacade;



    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public APIResponse addComment(ReqNewsComment reqNewsComment) {
        logger.info("开始评论:{}",reqNewsComment.toString());
        Integer dynamicDetailsId = reqNewsComment.getDynamicDetailsId();
        TbNewsDetails tbNewsDetails = tbNewsDetailsMapper.selectByPrimaryKey(dynamicDetailsId); //动态

        if(tbNewsDetails != null && tbNewsDetails.getIsDelete() == Constants.IS_DELETE_FALSE) { // 动态存在并且未删除
            //未读消息数
            UnReadParam unReadParam = new UnReadParam();
            unReadParam.setUid(tbNewsDetails.getUid());
            unReadParam.setType(NewsUnReadService.NewsUnReadType.comment);
            unReadParam.setNewsId(dynamicDetailsId);
            unReadParam.setfUid(reqNewsComment.getUid());//消息发送者
            unReadParam.setToUid(tbNewsDetails.getUid());//消息接受者

            TbComment tbComment = new TbComment();
            tbComment.setModuleType(UserConstants.ModuleType.dynamic);
            tbComment.setModuleId(reqNewsComment.getDynamicDetailsId());
            tbComment.setUid(reqNewsComment.getUid());
            tbComment.setContent(reqNewsComment.getContent());
            tbComment.setCreateTime(new Date());
            tbComment.setToCommentId(reqNewsComment.getCommentId());
            tbComment.setType(UserConstants.comment);
            tbComment.setTouid(reqNewsComment.getToUid());
//            if (sensitiveServiceFacade.isExistsKey(reqNewsComment.getContent())){
//                tbComment.setIsDelete(true);
//            }else
//                tbComment.setIsDelete(false);
            // 校验回复评论是否存在\
            int boxType = BoxType.COMMENTS_MSG.value();
            if(reqNewsComment.getCommentId() > 0 ){ // 评论类型是回复
                TbComment tbCommentValid =tbCommentMapper.selectByPrimaryKey(reqNewsComment.getCommentId());
                if(tbCommentValid != null && !tbCommentValid.getIsDelete() ) { // 该条评论存在
                    unReadParam.setType(NewsUnReadService.NewsUnReadType.at);
                    unReadParam.setAtUid(tbCommentValid.getUid());
                    tbComment.setToCommentId(reqNewsComment.getCommentId());
                    tbComment.setTouid(tbCommentValid.getUid());
                    tbComment.setType(UserConstants.comment_replay); //回复
                    boxType = BoxType.REPLY_MSG.value();
                }else {
                    logger.info("该条评论已删除！");
                    return APIResponse.returnFail("该条评论已删除！");
                }
            }
            tbCommentMapper.insertSelective(tbComment);

            TbNewsDetails updateNd = new TbNewsDetails();
            updateNd.setId(tbNewsDetails.getId());
            updateNd.setSumComments(tbNewsDetails.getSumComments() + 1);
            tbNewsDetailsMapper.updateByPrimaryKeySelective(updateNd);

            /*** ===============  任务中心  =================== */
            UserTaskMsg userTaskMsg = new UserTaskMsg();
            userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__I_COMMENT.getId());
            userTaskMsg.setUid(reqNewsComment.getUid());
            sendMsgService.sendUserTaskMsg(userTaskMsg);

            /*** ===============  推送  =================== */

            TbUser tbUser = userQueryService.getUser(reqNewsComment.getUid());
            List<ImageObj> lstImg = newsImagesService.getDynamicImages(dynamicDetailsId);
            String imageUrl = "" ;
            if(lstImg != null && lstImg.size() > 0)
                imageUrl = lstImg.get(0).getImageUrl() ;
           // sendMsgService.pushDynamicMsg(tbUser,tbNewsDetails.getUid(),tbComment.getTouid(),dynamicDetailsId,reqNewsComment.getContent(),boxType,imageUrl);
            unReadParam.setDynamicImg(imageUrl);
            if(tbNewsDetails.getUid().intValue() != reqNewsComment.getUid().intValue())
                newsUnReadService.addNewsUnRead(unReadParam);
            logger.info("评论成功");
            return APIResponse.returnSuccess();
        }
        logger.info("动态已删除！");
        return APIResponse.returnFail("动态已删除！");

    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public APIResponse delComment(ReqNewsCommentDel reqNewsCommentDel) {
        logger.info("开始删除评论:{}",reqNewsCommentDel.toString());

        TbComment tbComment = tbCommentMapper.selectByPrimaryKey(reqNewsCommentDel.getCommentId());
        if (tbComment != null ){
            if(tbComment.getIsDelete()){
                logger.info("改评论已经被删除!");
                return APIResponse.returnFail("改评论已经被删除!");
            }
            if(tbComment.getUid().intValue() != reqNewsCommentDel.getUid().intValue()){
                logger.info("嗨，不能删除其他小伙伴的评论哦!");
                return APIResponse.returnFail("嗨，不能删除其他小伙伴的评论哦!");
            }
            TbComment updateTbComment = new TbComment();
            updateTbComment.setId(tbComment.getId());
            updateTbComment.setIsDelete(true);
            tbCommentMapper.updateByPrimaryKeySelective(updateTbComment);

            TbNewsDetails tbNewsDetails = tbNewsDetailsMapper.selectByPrimaryKey(reqNewsCommentDel.getNewsId()); //动态
            TbNewsDetails updateNewsDetails = new TbNewsDetails();
            updateNewsDetails.setId(tbNewsDetails.getId());
            updateNewsDetails.setSumComments(tbNewsDetails.getSumComments() - 1);
            tbNewsDetailsMapper.updateByPrimaryKeySelective(updateNewsDetails);
            logger.info("删除评论成功！");
            return APIResponse.returnSuccess();
        }
        logger.info("评论不存在！");
        return APIResponse.returnFail("评论不存在！");

    }


    @Override
    public APIResponse queryComment(ReqNewsComment reqNewsComment) {
        logger.info("开始获取动态评论列表：{}",reqNewsComment.toString());
        TbNewsDetails tbNewsDetails = tbNewsDetailsMapper.selectByPrimaryKey(reqNewsComment.getDynamicDetailsId()); //动态
        if(tbNewsDetails != null && tbNewsDetails.getIsDelete() != Constants.IS_DELETE_TRUE ){ //动态存在
            try {
                reqNewsComment.setModuleType(UserConstants.ModuleType.dynamic);
                return  dynamicCommentService.findDynamicComment(reqNewsComment);
            } catch (Exception e) {
                logger.error("{}",e);
                return APIResponse.returnFail("系统异常！！");
            }
        }
        logger.info("动态不存在！");
        return APIResponse.returnFail("动态不存在！");
    }


    public List<TbComment> batchQueryById(List<Integer> newIds){
        TbCommentExample tbCommentExample = new TbCommentExample();
        TbCommentExample.Criteria criteria = tbCommentExample.createCriteria();
        criteria.andIsDeleteEqualTo(false);
        criteria.andModuleTypeEqualTo(UserConstants.ModuleType.dynamic);
        criteria.andModuleIdIn(newIds);
        tbCommentExample.setOrderByClause( " create_time desc");
        List<TbComment>  tbComments = tbCommentMapper.selectByExample(tbCommentExample);
        return tbComments;
    }
}
